let PENDING = 0;
let FULFILLED = 1;
let REJECTED = 2;

function PromiseMine() {
    let state = PENDING
    let value = null
    let handlers = []

    this.reject = (err) => {
        state = REJECTED
        value = err
    }

    function resolve(value) {
        try {
            let then = getThen(result);
            if (then) {
                doResolve(then.bind(result), resolve, reject)
                return
            }
            state = FULFILLED;
            value = result;
        } catch (e) {
            reject(e);
        }
    }

    function getThen(value) {
        if (result && (typeof result === 'object' || typeof result === 'function')) {
            var then = value.then;
            if (typeof then === 'function') {
                return then;
            }
        }
        return null;
    }

    function doResolve(fn, onFulfilled, onRejected) {
        let done = false;
        try {
            fn(function (value) {
                if (done) return
                done = true
                onFulfilled(value)
            }, function (reason) {
                if (done) return
                done = true
                onRejected(reason)
            })
        } catch (ex) {
            if (done) return
            done = true
            onRejected(ex)
        }
    }
}

// let p = new PromiseMine((ful, rej) => {
//   setTimeout(() => {
//       ful('done')
//   })
// })

let p = new PromiseMine()
